package common;

import java.util.Map;
import java.util.PriorityQueue;
import java.util.TreeMap;

/**
 * 字符排序
 *
 * @author K
 * @date 2022/5/18 9:26
 */
public class CharacterOrder {

    /**
     * 小顶堆 降序排列
     * 1 字母大于数字 √
     * 2 字母降序 √
     * 3 数字降序 √
     * 4 出现次数统计 ×
     */
    public static String sort(String str) {
        PriorityQueue<Character> minHeap = new PriorityQueue<>((o1, o2) -> {
            if (Character.isDigit(o1) && Character.isDigit(o2)) {
                return Integer.parseInt(String.valueOf(o2)) - (Integer.parseInt(String.valueOf(o1)));
            } else if (Character.isLetter(o1) && Character.isLetter(o2)) {
                return o2 - o1;
            } else {
                if (Character.isLetter(o2)) {
                    return 1;
                } else {
                    return -1;
                }
            }
        });

        Map<Character, Integer> map = new TreeMap<>();
        for (char c : str.toCharArray()) {
            minHeap.offer(c);
            map.put(c, map.getOrDefault(c, 0) + 1);
        }

        StringBuilder sb = new StringBuilder();
        while (!minHeap.isEmpty()) {
            char c = minHeap.poll();
            if (sb.toString().contains(String.valueOf(c))) {
                continue;
            }
            Integer count = map.get(c);
            for (int i = 0; i < count; i++) {
                sb.append(c);
            }
        }

        String s = sb.toString();
        return s;
    }

}